import json, os, sys
import urllib.request
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
# sys.path.append(BASE_DIR)
from globally import Sourceslists_Dir



# 接口信息
# http://archive1.kylinos.cn:59546/client_v1/-d41d8cd98f00b204e9800998ecf8427e/ + serial(59965048)
CpuList = ["arm64", "amd64", "loongarch64", "mips64el"]


def main():
    end = 0
    while not end:
        serialnumber = input("请输入服务序列号：").lstrip().rstrip()
        if serialnumber.isdigit():
            dl_serial_sourcelist(serialnumber)
            choose = input("是否需要导入其他服务序列号 (Y/N)：").lstrip().rstrip()
            while True:
                if choose == "N" or choose == "n":
                    end = 1
                    break
                elif choose == "Y" or choose == "y":
                    break
                else:
                    print("输入错误，请重新输入")
        else:
            print("服务序列号输入错误，请重新输入")

def dl_serial_sourcelist(serialnumber):
    url = "http://archive1.kylinos.cn:59546/client_v1/-d41d8cd98f00b204e9800998ecf8427e/" + serialnumber
    headers = {
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
        'Host': 'httpbin.org'
    }
    req = urllib.request.Request(url=url, headers=headers, method='GET')
    re = urllib.request.urlopen(req)
    response = json.loads(re.read())
    print(response["sources.list"])
    if response["sources.list"] != 'null':
        while True:
            cpuinfo = input("请输入cpu架构信息，可选有{}: ".format(CpuList))
            if cpuinfo in CpuList:
                break
            else:
                print("架构输入错误，请重新输入")
        dest = Sourceslists_Dir + '{}_{}'.format(serialnumber, cpuinfo)
        fd = open(dest, 'w', encoding='utf-8')
        for mumber in json.loads(response["sources.list"]):
            fd.write(mumber["source"] + '\n')
        fd.close()
        print('下载完成 —— 服务序列号：{}  架构：{}'.format(serialnumber, cpuinfo))
    else:
        print("未找到服务序列号 {} 的源地址".format(serialnumber))

if __name__ == '__main__':
    dl_serial_sourcelist("23227011")


